package com.david.core.imgloader;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Handler;
import android.util.LruCache;
import android.widget.ImageView;

import com.david.core.imgloader.bean.ImgCachedInfo;
import com.david.core.imgloader.bean.ImgRequestInfo;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Objects;

class LruImageRequestTask implements Runnable {
    private Context applicationContext;
    private String url;
    private String imageID;
    private String pageName;
    private boolean skipMemoryCache;
    private int errorImgId;
    private Handler mHandler;
    private volatile LruCache<String, WeakReference<ImgCachedInfo>> mImageCache;
    private volatile HashMap<String, ImgRequestInfo> imageViewMap;
    private LruImageLoader.IImageSavedListener imageSavedListener;

    public LruImageRequestTask(Context applicationContext, String url, String imageID, String pageName,
                               int errorImgId, Handler mHandler, LruCache<String,
            WeakReference<ImgCachedInfo>> mImageCache, HashMap<String, ImgRequestInfo> imageViewMap) {
        this.applicationContext = applicationContext;
        this.url = url;
        this.imageID = imageID;
        this.pageName = pageName;
        this.errorImgId = errorImgId;
        this.mHandler = mHandler;
        this.mImageCache = mImageCache;
        this.imageViewMap = imageViewMap;
    }

    public LruImageRequestTask(Context applicationContext, String url, String imageID, String pageName,
                               int errorImgId, Handler mHandler, LruCache<String,
            WeakReference<ImgCachedInfo>> mImageCache, HashMap<String,
            ImgRequestInfo> imageViewMap,
                               LruImageLoader.IImageSavedListener imageSavedListener) {
//        this.applicationContext = applicationContext;
//        this.url = url;
//        this.imageID = imageID;
//        this.pageName = pageName;
//        this.errorImgId = errorImgId;
//        this.mHandler = mHandler;
//        this.mImageCache = mImageCache;
//        this.imageViewMap = imageViewMap;
//        this.imageSavedListener = imageSavedListener;
        this(applicationContext, url,imageID,pageName,errorImgId,mHandler,mImageCache,imageViewMap,imageSavedListener, false);
    }

    public LruImageRequestTask(Context applicationContext, String url, String imageID, String pageName,
                               int errorImgId, Handler mHandler, LruCache<String,
            WeakReference<ImgCachedInfo>> mImageCache, HashMap<String,
            ImgRequestInfo> imageViewMap,
                               LruImageLoader.IImageSavedListener imageSavedListener,
                               boolean skipMemoryCache) {
        this.applicationContext = applicationContext;
        this.url = url;
        this.imageID = imageID;
        this.pageName = pageName;
        this.errorImgId = errorImgId;
        this.mHandler = mHandler;
        this.mImageCache = mImageCache;
        this.imageViewMap = imageViewMap;
        this.imageSavedListener = imageSavedListener;
        this.skipMemoryCache = skipMemoryCache;
    }

    @Override
    public void run() {
        InputStream is = null;
        try {
            //创建一个url对象
            URL rawUrl = new URL(url);
            //设置超时时间
            HttpURLConnection urlConn = (HttpURLConnection) rawUrl.openConnection();
            urlConn.setConnectTimeout(5000);
            urlConn.setReadTimeout(5000);
//            urlConn.setUseCaches(true);
//            urlConn.setRequestProperty("Cache-Control", "only-if-cached,max-age=2147483647");
            urlConn.connect();

            int code = urlConn.getResponseCode();
            if (code != 200) {
                if (errorImgId > 0) {
                    mHandler.post(() -> LruImageLoaderUtils.setImage(imageViewMap, imageID, true, errorImgId, null));
                } else {
                    imageViewMap.remove(imageID);
                }
                return;
            }

            //打开URL对应的资源输入流
            is = urlConn.getInputStream();


            String filePath = applicationContext.getExternalCacheDir() + File.separator + imageID;


            /*开始解析图片*/

            int maxSize = 0;
            if (imageViewMap.get(imageID) != null && Objects.requireNonNull(imageViewMap.get(imageID)).getImageViews() != null) {
                for (ImageView itemImgView : Objects.requireNonNull(imageViewMap.get(imageID)).getImageViews()) {
                    if (itemImgView.getWidth() > maxSize) {
                        maxSize = itemImgView.getWidth();
                    }
                }
            }

            Bitmap bitmap;
            if (urlConn.getContentLength() > 300000) {//大于300k的先存文件
                LruImageLoaderUtils.writeToFile(is, filePath);
                bitmap = LruImageLoaderUtils.loadImage(imageID, maxSize);
            } else {//其他直接获取bitmap并存储
                byte[] byteArray = LruImageLoaderUtils.getBytesInputStream(is);

                bitmap = LruImageLoaderUtils.loadImage(byteArray, maxSize);

                LruImageLoaderUtils.writeToFile(byteArray, filePath);
            }

            /*解析图片完成*/

            //关闭输入流
            is.close();


            ImgCachedInfo cachedInfo = new ImgCachedInfo();
            cachedInfo.setTag(pageName);
            cachedInfo.setBitmap(bitmap);
            /*开始缓存及显示图片*/
            WeakReference<ImgCachedInfo> weakReference = new WeakReference<>(cachedInfo);
            mImageCache.put(imageID, weakReference);

            mHandler.post(() -> {
                if (mImageCache.get(imageID) != null) {
                    LruImageLoaderUtils.setImage(imageViewMap, imageID, false, errorImgId, mImageCache.get(imageID).get().getBitmap());
                } else {
                    if (errorImgId > 0) {
                        LruImageLoaderUtils.setImage(imageViewMap, imageID, true, errorImgId, null);
                    } else {
                        removeRequest(imageID);
                    }
                }
                if (skipMemoryCache) {
                    mImageCache.remove(imageID);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();

            if (errorImgId > 0) {
                mHandler.post(() -> LruImageLoaderUtils.setImage(imageViewMap, imageID, true, errorImgId, null));
            } else {
                removeRequest(imageID);
            }
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (imageSavedListener != null) {
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (imageSavedListener != null) {
                            if (LruImageLoaderUtils.isImgIdCached(imageID)) {
                                imageSavedListener.onImageSaved(LruImageLoader.getApplicationContext().getExternalCacheDir() + File.separator + imageID);
                            } else {
                                imageSavedListener.onImageSaveFail("image download fail,please check log for reason!");
                            }
                        }
                    }
                });
            }
        }
    }

    private void removeRequest(String imageID) {
        ImgRequestInfo requestInfo = imageViewMap.remove(imageID);
        if (requestInfo != null) {
            requestInfo.getImageViews().clear();
            requestInfo.setImageViews(null);
            requestInfo.setTag(null);
            requestInfo.setUrl(null);
        }
    }
}
